package org.rambadger.command.resource;

import com.fasterxml.jackson.annotation.JsonProperty;
import org.hibernate.validator.constraints.NotBlank;
import org.mongojack.JacksonDBCollection;
import org.rambadger.command.auth.AuthToken;
import org.rambadger.command.auth.AuthUser;
import org.rambadger.command.axon.JCollection;
import org.rambadger.command.providers.ConfigParam;
import org.rambadger.command.validation.UrlIdentifier;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.NewCookie;
import javax.ws.rs.core.Response;

@Path("/login")
public class LoginResource {
    public static class LoginJSON {
        @JsonProperty("username") @UrlIdentifier @NotNull String username;
        @JsonProperty("password") @NotBlank String password;
    }

    public static final String WRONG_PASSWORD_STRING = "Bad username/password combination";
    @JCollection(type=AuthToken.class)
    private JacksonDBCollection<AuthToken, String> tokens = null;
    @JCollection(type=AuthUser.class)
    private JacksonDBCollection<AuthUser, String> users = null;
    private @ConfigParam("authCookieName") String cookieName;


    @POST
    @Consumes(MediaType.APPLICATION_JSON)
//    @Consumes(MediaType.WILDCARD)
    public Object doLogin(@Valid LoginJSON json) {

        AuthUser userFound = users.findOneById(json.username);
        if (userFound == null) {
            return Response.status(Response.Status.UNAUTHORIZED).entity(WRONG_PASSWORD_STRING).build();
        }

        if (userFound.checkPassword(json.password)) {
            //TODO: Un-hardcode the expiration
            //TODO: Move the NewCookie into the AuthToken
            AuthToken newToken = AuthToken.getNewTokenForUser(json.username);
            tokens.insert(newToken);

            NewCookie authCookie = new NewCookie(cookieName, newToken.getKey());
            return Response.ok().cookie(authCookie).build();
        } else {
            return Response.status(Response.Status.UNAUTHORIZED).entity(WRONG_PASSWORD_STRING).build();
        }
    }
}
